package com.sinosoft.cloud.access.handler;

import com.sinosoft.cloud.access.net.MessageObject;
import com.sinosoft.cloud.access.router.Router;
import com.sinosoft.cloud.access.router.RouterBean;
import com.sinosoft.cloud.common.SpringContextUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

/**
 * cloud-netty
 *
 * @title: cloud-netty
 * @package: com.sinosoft.cloud.access.handler
 * @author: yangming
 * @date: 2017/12/2 下午9:30
 */
public class RouterHandler extends AbstractHandler {
    @Override
    MessageObject dealMessage(ChannelHandlerContext ctx, MessageObject messageObject) {

        if (messageObject.getHasError() || accessControl.getBarrierControl()){
            return messageObject;
        }

        Router router = getRouter();
        if (router.msgRouter(messageObject.getTranData())) {
            RouterBean routerBean = SpringContextUtils.getBeanByClass(RouterBean.class);
            String msg = messageObject.getOriginalMsg();
            logger.info("需要发送CIP的报文：" + messageObject.getOriginalMsg());
            ByteBuf encoded = Unpooled.copiedBuffer(msg.getBytes());
            routerBean.sendToRouter(getAccessName(), ctx, encoded, messageObject);
            messageObject.setNext(MessageObject.Type.shutDown);
        } else {
            messageObject.setNext(MessageObject.Type.fireChannelRead);
        }
        return messageObject;
    }
}
